package com.sean.common.action;

import java.io.PrintWriter;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.util.WebUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.sean.common.page.Pagination;
import com.sean.common.service.BaseService;
import com.sean.common.utils.DateUtils;
import com.sean.common.utils.JsonUtils;
import com.sean.common.utils.StringUtils;

/**
 * Struts2 Action父类 所有Action类需要继承
 * 
 * @author XinWang
 * 
 */
public abstract class BaseAction extends ActionSupport {

	protected static final String ENCODING_UTF8 = "UTF-8";

	protected static final String ENCODING_GBK = "GBK";
	
	protected static final String ENCODING_ISO = "ISO-8859-1";

	protected static final String PAGE_NUM_KEY = "page";

	protected static final String PAGE_SIZE_KEY = "rows";

	protected static final long serialVersionUID = 1L;

	protected static final Log log = LogFactory.getLog(BaseService.class);
	// 传入参数
	protected Long id;

	// 传入参数
	protected List<Long> ids;
	
	//ajax放回结果集
	protected PageResult res = new PageResult();
	
	/**
	 * 获取恶意访问回复.
	 * @return
	 */
	protected PageResult getErrRes() {
		return this.getErrRes("请正常使用本系统.");
	}
	
	/**
	 * 获取恶意访问回复.
	 * @param msg
	 * @return
	 */
	protected PageResult getErrRes(String msg) {
		return new PageResult(-1, msg);
	}
	/**
	 * 错误回复.
	 * @param msg
	 * @return
	 */
	protected PageResult getErrRes(int code, String msg) {
		return new PageResult(code, msg);
	}

	/**
	 * 获取分页信息.
	 * 
	 * @return
	 */
	protected Pagination getPagination() {
		Pagination pagination = new Pagination();
		String pageNumStr = this.get(PAGE_NUM_KEY);
		if (StringUtils.isNotBlank(pageNumStr)) {
			try {
				int pageNum = Integer.parseInt(pageNumStr.trim());
				pagination.setPageNum(pageNum);
			} catch (NumberFormatException e) {
			}
		}
		String pageSizeStr = this.get(PAGE_SIZE_KEY);
		if (StringUtils.isNotBlank(pageSizeStr)) {
			try {
				int pageSize = Integer.parseInt(pageSizeStr.trim());
				pagination.setPageSize(pageSize);
			} catch (NumberFormatException e) {
			}
		}
		return pagination;
	}

	/**
	 * 获取分页信息和所有查询参数.
	 * 
	 * @return
	 */
	protected Pagination getPaginationForParameter() {
		Pagination pagination = this.getPagination();
		Map<String, Object> parameters = WebUtils.getParametersStartingWith(this.getRequest(), "s_");
		pagination.putParams(parameters);
		return pagination;
	}

	/**
	 * 向页面输出字符
	 * 
	 * @param output
	 * @return
	 */
	protected void out(String output, String encoding) {
		PrintWriter out = null;
		try {
			// 获取原始的PrintWriter对象,以便输出响应结果,而不用跳转到某个试图
			HttpServletResponse response = getResponse();
			// 设置字符集
			response.setCharacterEncoding(encoding);

			out = response.getWriter();
			// 直接输入响应的内容
			out.write(output);

			out.flush();
		} catch (Exception e) {
			log.error("向页面输出数据出错", e);
		} finally {
			if (out != null)
				out.close();
		}
	}

	/**
	 * 输出访问状态码
	 * 
	 * @param code
	 */
	protected void setStatus(int code) {
		this.getResponse().setStatus(code);
	}

	/**
	 * 获取页面提交参数.
	 * 
	 * @param key
	 * @return
	 */
	protected String get(String key) {
		return this.getRequest().getParameter(key);
	}
	
	/**
	 * 获取页面提交参数.
	 * 
	 * @param key
	 * @return
	 */
	protected Object get(String key, ParameterType type) {
		String value = this.getRequest().getParameter(key);
		if(value == null) return null;
		if(type == ParameterType.LONG) {
			return Long.parseLong(value.trim());
		} else if(type == ParameterType.FLOAT) {
			return Float.parseFloat(value.trim());
		}  else if(type == ParameterType.DOUBLE) {
			return Double.parseDouble(value.trim());
		} else if(type == ParameterType.INTEGER) {
			return Integer.parseInt(value.trim());
		} else if(type == ParameterType.DATE) {
			try {
				return DateUtils.parse(value.trim(), "yyyy-MM-dd");
			} catch (ParseException e) {}
		} else if(type == ParameterType.TIME) {
			return DateUtils.getDateByString(value.trim());
		} else if(type == ParameterType.BOOLEAN) {
			return Boolean.valueOf(value);
		}
		return value;
	}
	
	

	/**
	 * 向页面输出字符. 默认UTF-8字符集
	 * 
	 * @param output
	 * @return
	 */
	protected void out(String output) {
		out(output, ENCODING_UTF8);
	}

	/**
	 * 将对象以Json方式输出到页面上
	 * 
	 * @param src
	 */
	protected void outJson(Object res) {
		this.out(JsonUtils.getJson(res));
	}

	/**
	 * 以Script标签包含输出字符
	 * 
	 * @param script
	 */
	protected void outScript(String script) {
		this.outScript(script, "UTF-8");
	}

	protected void outScript(String script, String encoding) {
		String outStr = "<HTML>\n<HEAD>\n<script type=\"text/javascript\">\n" + script + "\n" + "</script>\n</HEAD>\n</HTML>";
		this.out(outStr, encoding);
	}

	/**
	 * 添加Request属性
	 * 
	 * @param key
	 * @param obj
	 */
	protected void put(String key, Object obj) {
		getRequest().setAttribute(key, obj);
	}

	/**
	 * 获取HttpServletRequest
	 * 
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 获取HttpSession
	 * 
	 * @return
	 */
	protected HttpSession getSessiont() {
		return ServletActionContext.getRequest().getSession();
	}

	/**
	 * 获取HttpResponse
	 * 
	 * @return HttpServletResponse
	 */
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getId() {
		return id;
	}

	public List<Long> getIds() {
		return ids;
	}

	public void setIds(List<Long> ids) {
		this.ids = ids;
	}

	/**
	 * ajax返回处理结果
	 * @author XinWang
	 *
	 */
	public class PageResult {
		
		private int code = 1;
		
		private String msg;
		
		private Map<String, Object> attributes = new HashMap<String, Object>();
		
		public PageResult() {
		}
		/**
		 * 处理出错结果集创建.
		 * @param errorCode
		 * @param errorTextKey
		 */
		public PageResult(int errorCode, String errorTextKey) {
			this.code = errorCode;
			this.msg = errorTextKey;
		}
		public PageResult(String errorCode, String errorTextKey) {
			this.code = Integer.parseInt(errorCode);
			this.msg = errorTextKey;
		}
		public void put(String arg0, Object arg1) {
			attributes.put(arg0, arg1);
		}
		public int getCode() {
			return code;
		}
		public String getMsg() {
			return msg;
		}
	}
	
	protected PageResult getSucceedPageResult() {
		return new PageResult();
	}
	
	/**
	 * 参数类型.
	 * @author XinWang
	 *
	 */
	protected enum ParameterType{
		INTEGER,
		LONG,
		STRING,
		DATE,
		FLOAT, 
		TIME, 
		DOUBLE,
		BOOLEAN
	}
}
